package com.example.fund.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.util.EncodingUtils;

import android.app.Activity;
import android.content.Context;

public class AssetsUtil {

	/**
	 * 从resource的asset中读取文件数据
	 * @param activity
	 * @param fileName
	 * @return
	 */
	public static String getAssetsFile(Activity activity,String fileName)
	{
		String res=""; 
		try{   
			//得到资源中的asset数据流  
			InputStream in = activity.getResources().getAssets().open(fileName);   
			int length = in.available();           
			byte [] buffer = new byte[length];          

			in.read(buffer);              
			in.close();  
			res = EncodingUtils.getString(buffer, "UTF-8");       
		}catch(Exception e){   
			e.printStackTrace();           
		}
		
		return res;
	}
	
	/**
	 * 从resource的asset中读取文件数据
	 * @param activity
	 * @param fileName
	 * @return
	 */
	public static byte[] getAssetsFileInputStream(Activity activity,String fileName)
	{
		byte[] buffer=null;
		try{   
			//得到资源中的asset数据流  
			InputStream in = activity.getResources().getAssets().open(fileName);   
			int length = in.available();           
			buffer = new byte[length];          

			in.read(buffer);              
			in.close();  
		}catch(Exception e){   
			e.printStackTrace();           
		}
		
		return buffer;
	}
	
	/**
	 * 从assets复制文件到data目录
	 * @param activity
	 * @param fileName
	 * @return
	 */
	public static boolean assetsCopyToData(Activity activity,String fileName)
	{  
	       boolean bIsSuc = true;  
	       InputStream inputStream = null;  
	       OutputStream outputStream = null;  
	         
	        try { 
	            FileInputStream fin = activity.openFileInput(fileName); 
	            fin.close(); 
//	            return true; //此文件已存在，则不复制
	        } catch (Exception e) { 
	            e.printStackTrace(); 
	        } 
	         
	       try {  
	           inputStream = activity.getResources().getAssets().open(fileName);  
	           outputStream = activity.openFileOutput(fileName, Context.MODE_PRIVATE);  
	             
	           int nLen = 0 ;  
	             
	           byte[] buff = new byte[1024*1];  
	           while((nLen = inputStream.read(buff)) > 0){  
	              outputStream.write(buff, 0, nLen);  
	           }  
	           //完成  
	       } catch (IOException e) {  
	           bIsSuc = false;  
	       }finally{  
	           try {  
	              if (outputStream != null){  
	                  outputStream.close();  
	              }  
	                
	              if (inputStream != null){  
	                  inputStream.close();  
	              }  
	           } catch (IOException e) {  
	              bIsSuc = false;  
	           }  
	             
	       }  
	         
	       return bIsSuc;  
	    } 
}
